import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AccountingApp extends JFrame {
    private List<Record> records = new ArrayList<>();
    private DefaultTableModel tableModel;
    private JTable table;
    private String filePath = "records.txt";

    // 收入和支出类别
    private static final String[] INCOME_CATEGORIES = {"工资", "奖金", "投资收益", "其他收入"};
    private static final String[] EXPENSE_CATEGORIES = {"餐饮", "交通", "住房", "娱乐", "购物", "医疗", "其他支出"};

    public AccountingApp() {
        super("个人记账软件");
        loadRecords();
        initUI();
        updateTable();
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    private void initUI() {
        JPanel mainPanel = new JPanel(new BorderLayout());

        // 顶部表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        JLabel dateLabel = new JLabel("日期:");
        JTextField dateField = new JTextField(15);
        dateField.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));

        JLabel typeLabel = new JLabel("类型:");
        JComboBox<String> typeCombo = new JComboBox<>(new String[]{"收入", "支出"});

        JLabel categoryLabel = new JLabel("类别:");
        JComboBox<String> categoryCombo = new JComboBox<>(INCOME_CATEGORIES);

        JLabel amountLabel = new JLabel("金额:");
        JTextField amountField = new JTextField(10);

        JLabel descLabel = new JLabel("备注:");
        JTextField descField = new JTextField(20);

        JButton addButton = new JButton("添加记录");
        JButton clearButton = new JButton("清空记录");

        // 监听类型选择变化，更新类别下拉框
        typeCombo.addActionListener(e -> {
            String selectedType = (String) typeCombo.getSelectedItem();
            categoryCombo.setModel(new DefaultComboBoxModel<>(
                    selectedType.equals("收入") ? INCOME_CATEGORIES : EXPENSE_CATEGORIES
            ));
        });

        // 底部状态栏
        JPanel statusPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel balanceLabel = new JLabel();
        statusPanel.add(balanceLabel);

        // 更新余额标签
        updateBalanceLabel(balanceLabel);

        // 添加记录按钮事件
        addButton.addActionListener(e -> {
            try {
                String date = dateField.getText();
                String type = (String) typeCombo.getSelectedItem();
                String category = (String) categoryCombo.getSelectedItem();
                double amount = Double.parseDouble(amountField.getText());
                String description = descField.getText();

                // 简单的日期格式验证
                new SimpleDateFormat("yyyy-MM-dd").parse(date);

                records.add(new Record(date, type, category, amount, description));
                saveRecords();
                updateTable();

                // 清空输入框
                amountField.setText("");
                descField.setText("");
                // 更新余额标签
                updateBalanceLabel(balanceLabel);
                JOptionPane.showMessageDialog(this, "记录添加成功！");

            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(this, "日期格式错误，应为yyyy-MM-dd", "错误", JOptionPane.ERROR_MESSAGE);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "金额格式错误", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 清空记录按钮事件
        clearButton.addActionListener(e -> {
            int confirm = JOptionPane.showConfirmDialog(this, "确定要清空所有记录吗？", "确认", JOptionPane.YES_NO_OPTION);
            if (confirm == JOptionPane.YES_OPTION) {
                records.clear();
                saveRecords();
                updateTable();
            }
        });

        // 布局表单控件
        int row = 0;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(dateLabel, gbc);
        gbc.gridx = 1; gbc.gridy = row; formPanel.add(dateField, gbc);
        gbc.gridx = 2; gbc.gridy = row; formPanel.add(typeLabel, gbc);
        gbc.gridx = 3; gbc.gridy = row; formPanel.add(typeCombo, gbc);
        row++;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(categoryLabel, gbc);
        gbc.gridx = 1; gbc.gridy = row; formPanel.add(categoryCombo, gbc);
        gbc.gridx = 2; gbc.gridy = row; formPanel.add(amountLabel, gbc);
        gbc.gridx = 3; gbc.gridy = row; formPanel.add(amountField, gbc);
        row++;
        gbc.gridx = 0; gbc.gridy = row; formPanel.add(descLabel, gbc);
        gbc.gridx = 1; gbc.gridy = row; gbc.gridwidth = 3; formPanel.add(descField, gbc);
        row++;
        gbc.gridx = 0; gbc.gridy = row; gbc.gridwidth = 2; formPanel.add(addButton, gbc);
        gbc.gridx = 2; gbc.gridy = row; gbc.gridwidth = 2; formPanel.add(clearButton, gbc);

        // 表格面板
        String[] columnNames = {"日期", "类型", "类别", "金额", "备注"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);



        // 添加所有面板到主面板
        mainPanel.add(formPanel, BorderLayout.NORTH);
        mainPanel.add(scrollPane, BorderLayout.CENTER);
        mainPanel.add(statusPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private void updateTable() {
        tableModel.setRowCount(0);
        for (Record record : records) {
            Object[] rowData = {
                    record.getDate(),
                    record.getType(),
                    record.getCategory(),
                    record.getAmount(),
                    record.getDescription()
            };
            tableModel.addRow(rowData);
        }
    }

    private void updateBalanceLabel(JLabel label) {
        double income = 0, expense = 0;
        for (Record record : records) {
            if (record.getType().equals("收入")) {
                income += record.getAmount();
            } else {
                expense += record.getAmount();
            }
        }
        double balance = income - expense;
        label.setText(String.format("总收入: %.2f  总支出: %.2f  余额: %.2f", income, expense, balance));
    }

    private void saveRecords() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (Record record : records) {
                writer.write(record.toString());
                writer.newLine();
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "保存记录失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void loadRecords() {
        File file = new File(filePath);
        if (!file.exists()) return;

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Record record = Record.fromString(line);
                if (record != null) {
                    records.add(record);
                }
            }
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, "加载记录失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new AccountingApp().setVisible(true);
        });
    }
}